//
// Copyright (c) 2014, 保留所有权利。
//
// RecommendUtil.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 上午9:47:58
//
// 
//
package com.vanke.agent.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;

import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.common.log.LoggerUtil;

/**
 *
 */
public class RecommendUtil {
	private static Logger log=LoggerUtil.getLoggerByName("recommend_util");
	public static void updateCstStatusForTrade(Connection con,long cstGuid,String recommendGUID,
			String oldTradeGUID,double oldMoney,String OldtradeStatusTrack,
			int followType,Timestamp followTime,
			String tradeGUID,double amount,double updateMoney,
			String tradeStatusTrack,int state) {
		if (cstGuid == 0) {
			return ;
		}
		PreparedStatement stmt = null;
		try {
		String table = CstUtil.calcCstSplitTable("prm_Agent_Cst_Recommed_",cstGuid);
		String s=tradeStatusTrack.trim();
		oldTradeGUID=(oldTradeGUID==null)?"":oldTradeGUID;
		if(state==C.TRADE_STATUS_MODIFY && (!"转签约".equals(s)||!"转认购".equals(s)||!"转小订".equals(s))){
			//修改
			amount=oldMoney-updateMoney+amount;
			//更新不改了，否则统计不到了
//			if(followType==C.FOLLOW_ORDER){
//				followType=C.FLAG_ORDER_CHANGE;
//			}else if(followType==C.FOLLOW_CONTRACT){
//				followType=C.FLAG_CONTRACT_CHANGE;
//			}
		}else if(state==C.TRADE_STATUS_NONE || state==C.TRADE_STATUS_NEW){
			//新增
			tradeGUID=oldTradeGUID+";"+tradeGUID;
			amount=oldMoney+amount;
		}else{
			//删除
			if(oldTradeGUID!=null){
				tradeGUID=oldTradeGUID.replace(";"+tradeGUID, "");
			}
			amount=oldMoney-amount;
			if(followType==C.FOLLOW_ORDER){
				followType=C.FLAG_ORDER_CHANGE;
			}else if(followType==C.FOLLOW_CONTRACT){
				followType=C.FLAG_CONTRACT_CHANGE;
			}
		}
		OldtradeStatusTrack=(OldtradeStatusTrack==null)?"":OldtradeStatusTrack+"-";
		tradeStatusTrack=OldtradeStatusTrack+tradeStatusTrack;
		String sql="update "+table+" set tradeStatus=? , tradeDate=? , tradeGUID=? ,amount=? ,tradeStatusTrack=? where RecommendGUID=? ";
		stmt = con.prepareStatement(sql);
		stmt.setInt(1, followType);
		stmt.setTimestamp(2, followTime);
		stmt.setString(3, tradeGUID);
		stmt.setDouble(4,amount);
		stmt.setString(5,tradeStatusTrack);
		stmt.setString(6, recommendGUID);
		log.info(sql+String.format(",{tradeStatus:%d,followTime:%s,tradeGUID:%s,amount:%s,tradeStatusTrack:%s,recommendGUID:%s,cstGUID:%d}",
				followType,followTime,tradeGUID,amount,tradeStatusTrack,recommendGUID,cstGuid));
		stmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(stmt);
		}
	}
	/**
	 * 更新售前客户状态
	 * @param con
	 * @param cstGuid
	 * @param recommendGUID
	 * @param cstStatus
	 * @param followType
	 * @param followTime
	 */
	public static void updateCstStatusForFollow(Connection con,long cstGuid,String recommendGUID,String cstStatus,int followType,Timestamp followTime,long oldTime) {
		if (cstGuid == 0) {
			return ;
		}
		PreparedStatement stmt = null;
		try {
		if(cstStatus!=null && Integer.parseInt(cstStatus.trim())==3 && followTime.before(new Timestamp(oldTime*1000l))){
			//客户已经是到访的不需要处理
				return;
		}
		String table = CstUtil.calcCstSplitTable("prm_Agent_Cst_Recommed_",cstGuid);
		String sql="update "+table+" set cstStatus=? , lastVisitDate=? where RecommendGUID=? ";
		stmt = con.prepareStatement(sql);
		stmt.setInt(1, followType);
		stmt.setTimestamp(2, followTime);
		stmt.setString(3, recommendGUID);
		log.info(sql+","+String.format("{cstGuid:%d,followType:%d,followTime:%s,recommendGUID:%s}",cstGuid,followType,followTime,recommendGUID));
		stmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(stmt);
		}
	}
	//返回推荐记录 RecommendGUID,cstStatus,tradeGUID,amount,tradeStatusTrack,tradeStatus,lastVisitDate
	public static String[] getAgentCstRecommed(Connection cons, long cstGuid,
			String projCode) {
		if (cstGuid == 0) {
			return null;
		}
		String table = CstUtil.calcCstSplitTable("prm_Agent_Cst_Recommed_",
				cstGuid);
		String sql = "select RecommendGUID,cstStatus,tradeGUID,amount,tradeStatusTrack,tradeStatus,case when lastVisitDate is null then 0 else UNIX_TIMESTAMP(lastVisitDate) end as lastVisitDate from " + table;
		sql += " where CstGUID=?";
		sql += " and projCode=? and enable=1 ";
		sql += " order by RecommTime desc";
		Connection bizCon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String firstLevelProjCode = Util.convertFistLevel(projCode);
			String popupProjCode = getPopularizeProjCode(bizCon, projCode);
//			log.info("--=="+sql);
			log.info("--=="+"{CstGUID="+cstGuid+",projCode="+(popupProjCode != null ? popupProjCode
					: firstLevelProjCode)+",sql:"+sql);
			stmt = bizCon.prepareStatement(sql);
			stmt.setLong(1, cstGuid);
			// 没找到，查找推广项目，找到按推广项目进行查找
			stmt.setString(2, (popupProjCode != null ? popupProjCode
					: firstLevelProjCode));
			rs = stmt.executeQuery();
			if (rs.next()) {
				//RecommendGUID,cstStatus,tradeGUID,amount,tradeStatusTrack,tradeStatus,lastVisitDate
				String[] asr=new String[]{
				rs.getString(1),
				rs.getInt(2)+"",
				rs.getString(3)==null?"":rs.getString(3),
				rs.getDouble(4)+"",
				rs.getString(5)==null?"":rs.getString(5),
				rs.getInt(6)+"",
				rs.getInt(7)+""
				};
				return asr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(rs, stmt, bizCon);
		}
		return null;
	} //~getLatestRecommendGUID
	public static String getLatestRecommendGUID(Connection cons, long cstGuid,
			String projCode) {
		if (cstGuid == 0) {
			return null;
		}
		String table = CstUtil.calcCstSplitTable("prm_Agent_Cst_Recommed_",
				cstGuid);
		String sql = "select RecommendGUID from " + table;
		sql += " where CstGUID=?";
		sql += " and projCode=? and enable=1 ";
		sql += " order by RecommTime desc";
		Connection bizCon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String firstLevelProjCode = Util.convertFistLevel(projCode);
			String popupProjCode = getPopularizeProjCode(bizCon, projCode);

			stmt = bizCon.prepareStatement(sql);
			stmt.setLong(1, cstGuid);
			// 没找到，查找推广项目，找到按推广项目进行查找
			stmt.setString(2, (popupProjCode != null ? popupProjCode
					: firstLevelProjCode));
			rs = stmt.executeQuery();
			if (rs.next()) {
				return rs.getString(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(rs, stmt, bizCon);
		}
		return null;
	} //~getLatestRecommendGUID

	private static String getPopularizeProjCode(Connection con, String projCode) {
		String sql = "select PopularizeProjCode from p_Project_Mapping where RealProjCode=?";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			stmt = con.prepareStatement(sql);
			stmt.setString(1, projCode);
			rs = stmt.executeQuery();
			if (rs.next()) {
				return rs.getString(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(rs, stmt, null);
		}
		return null;
	}

	//	private static String getFirstLevel(Connection con, String projCode) {
	//		String sql = "";
	//		PreparedStatement stmt = null;
	//		ResultSet rs = null;
	//		try {
	//		} catch (Exception e) {
	//			e.printStackTrace();
	//		} finally {
	//			ADataSource.close(rs, stmt, null);
	//		}
	//	}
} ///~
